﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using micsun.Data;
using System.Data;
using micsun.SqlDom;
using micsun.Logic;
using System.Collections;
using System.Web;
using System.ComponentModel;
using System.Web.UI.HtmlControls;

namespace micsun.Web.WebControls
{
    public class GridViewPlus : GridView, IPostBackEventHandler
	{
        public GridViewPlus()
            : base()
        {
            _aspager = new AspNetPager();
            
            ShowFooter = true;
        }
        private DataParameterCollection Parameters = new DataParameterCollection();//定位参数，每次搜索时会更新
        public DataTable SchemaTable;
        public string KeyIDName;
        public int[] KeyIDPosition = new int[] { 1 };
        private SelectType _selectType;
        [Browsable(true),        
        DefaultValue(SelectType.None)]
        public SelectType SelectType
        {
            get { return _selectType; }
            set { _selectType = value; }
        }
        private int _CurrentPageIndex = 1;
        private int _recordCount = 0;
        private AspNetPager _aspager;
        [Browsable(false)]
        //public AspNetPager Aspager
        //{
        //    get
        //    {
        //        return _aspager;
        //    }
        //}
        private bool _allowCustomPaging;
        [Browsable(true),
        DefaultValue(false)]
        public bool AllowCustomPaging
        {
            get { return _allowCustomPaging; }
            set { _allowCustomPaging = value; }
        }
        private string getCheckBoxString()
        {
            if (this.SelectType == SelectType.MultiSelect)
                return "CheckBox";
            else
                return "Radio";
        }

        #region DobuleClick...
        public event DoubleClick OnDblClick;	
        #region IPostBackEventHandler 成员

        void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)
        {
            throw new NotImplementedException();
        }

        #endregion
        #endregion

        #region sql语句生成器
        string _vselectList;
        public string VSelectList
        {
            get { return _vselectList; }
            set { _vselectList = value; }
        }
        string _selectList;
        public string SelectList
        {
            get { return _selectList; }
            set { _selectList = value; }
        }
        string _tableList;
        public string TableList
        {
            get { return _tableList; }
            set { _tableList = value; }
        }
        string _whereList;
        public string WhereList
        {
            get
            {
                string temp = _whereList + SearchCond;
                if (temp != null)
                {
                    if (temp.StartsWith(" and ")) temp = temp.Remove(0, 5);
                    if (temp.Trim() == string.Empty)
                        return null;
                }
                return temp;
            }
            set { _whereList = value; }
        }
        string _groupList;
        public string GroupList
        {
            get { return _groupList; }
            set { _groupList = value; }
        }
        string _havingList;
        public string HavingList
        {
            get { return _havingList; }
            set { _havingList = value; }
        }
        string _orderList;
        public string OrderList
        {
            get { return _orderList; }
            set { _orderList = value; }
        }
        public string getCountSql()
        {
            string temp = string.Empty;
            if (_selectList.TrimStart(' ').ToLower().StartsWith("distinct "))
            {//temp= "select count("+_selectList+") from "+_tableList ;
                temp = "select " + _selectList + " from " + _tableList;
                temp += (WhereList == null || WhereList == string.Empty) ? null : (" where " + WhereList);
                temp += (_groupList == null || _groupList == string.Empty) ? null : (" group by " + _groupList);
                temp += (_havingList == null || _havingList == string.Empty) ? null : (" HAVING  " + _havingList);
                //temp+=(_orderList==null || _orderList==string.Empty)?null:(" order by "+_orderList);
                temp = "select count(*) from (" + temp + ")";
            }
            else
            {
                temp = "select count(*) from " + _tableList;
                temp += (WhereList == null || WhereList == string.Empty) ? null : (" where " + WhereList);
                temp += (_groupList == null || _groupList == string.Empty) ? null : (" group by " + _groupList);
                temp += (_havingList == null || _havingList == string.Empty) ? null : (" HAVING  " + _havingList);
                //temp+=(_orderList==null || _orderList==string.Empty)?null:(" order by "+_orderList);
                if (_groupList != null && _groupList != string.Empty)
                    temp = "select count(*) from (" + temp + ")";
            }
            return temp;
        }
        public string getOrinSql()
        {
            string temp = "select " + ((_selectList == null || _selectList == string.Empty) ? " * " : "row_number() over(order by getdate()) as rownum, " + _selectList) + " from " + _tableList;
            temp += (WhereList == null || WhereList == string.Empty) ? null : (" where " + WhereList);
            temp += (_groupList == null || _groupList == string.Empty) ? null : (" group by " + _groupList);
            temp += (_havingList == null || _havingList == string.Empty) ? null : (" HAVING  " + _havingList);
            temp += (_orderList == null || _orderList == string.Empty) ? null : (" order by " + _orderList);
            return temp;
        }
        public string getPagerSql()
        {
            if (this.PageIndex < 0) this.PageIndex = 0;
            string s = string.Empty;
            if (this.PageIndex == 0)
            {
                s = "select top " + this.PageSize + " row_number() over(order by getdate()) as myrownum,* from (" + getOrinSql() + ") t";
            }
            else
            {
                s = "select top " + this.PageSize + " * from (" + getOrinSql() + ") t1 where t1.rownum not in (select top " + this.PageSize * this.PageIndex + " row_number() over(order by getdate()) from (" + getOrinSql() + ")t2)";
            }
            return s;
        }

        /// <summary>
        /// 获取keyID位置的sql语句
        /// </summary>
        /// <returns></returns>
        public string getPositionSql()
        {
            if (this.PageIndex < 0) this.PageIndex = 0;
            StringBuilder builder = new StringBuilder();
            builder.Append("select myrownum ")

                .Append(" from ")
                .Append("(select over(order by getdate()) as myrownum")
                .Append(KeyFeildNameList)
                .Append(" from (")
                .Append(getOrinSql())
                .Append(") tt ")
                .Append(") tt1 where ")
                .Append("rownum>=1 ")
                .Append(KeyFieldCondList);
            return builder.ToString();
        }
        public void AddCondAnd(string cond)
        {
            if (WhereList == string.Empty)
                WhereList = cond;
            else
                WhereList += " and " + cond;
        }

        public void AddCondOr(string cond)
        {
            if (WhereList == string.Empty)
                WhereList = cond;
            else
                WhereList = " (" + WhereList + ") " + " or " + cond;
        }
        #endregion
        
        #region 记录定位
        private string KeyFieldCondList;
        private string KeyFeildNameList;
        public int RecordPosition = -1;
        public string KeyIDValue;
        private int SingleSelectPostion;
        //记录定位必须知道key和keyvalue
        /// <summary>
        /// 生成KeyFieldList,KeyFieldCondList,Parameters
        /// </summary>
        /// <param name="KeyFieldName"></param>
        /// <param name="KeyFieldVale"></param>
        public void AddFindField(string KeyFieldName, object KeyFieldValue)
        {
            if (isGoodKeyName(KeyFieldName) && KeyFieldValue != null)
            {
                //不允许全为空格。
                if (KeyFieldValue.ToString().Trim() == string.Empty)
                {
                    return;
                }
                KeyFeildNameList += "," + KeyFieldName;
                //KeyFeildSumList+="||"+ trim(to_char(funid))||grpid
                string temp = KeyFieldName + getParameterExt();
                SqlParameterDeclaration pKeyFieldName = new SqlParameterDeclaration(temp);
                KeyFieldCondList += " and " + KeyFieldName + "=" + pKeyFieldName.Generate();
                Parameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp, KeyFieldValue));
            }
        }
        //用于没有翻页的时候定位，只适用于单选，不刷新的情况。
        public void RegisterFindScript()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("<script language=\"javascript\">\r\n")
                .Append("function _Set" + this.UniqueID + "KeyID() \r\n")
                .Append("{")
                .Append("var oObject = document.all.item('" + KeyIDName + "');")
                .Append("  if (oObject != null){")
                .Append("if (oObject.length != null){")
                .Append("for (i = 0; i < oObject.length; i++){")
                .Append("if(oObject(i).value=='" + KeyIDValue + "')oObject(i).checked=true;")
                .Append("}")
                .Append("}")
                .Append("else")
                .Append("{")
                .Append("oObject.checked=true;")
                .Append("}")
                .Append("}")
                .Append("}\r\n")
                .Append("_Set" + this.UniqueID + "KeyID();\r\n")
                .Append("</script>");
            Page.RegisterStartupScript(this.UniqueID + "__messageHandler1", builder.ToString());
        }
        #endregion
        #region  查询和二次查询
        private string SearchCond;
        private DataParameterCollection SearchParameters;
        /// <summary>
        /// 查询和二次查询条件
        /// </summary>
        public string AddSearchCond(string FieldName, string operater, string searchvalue, string valueType, SearchType searchType)
        {
            //因为searchvalue是从textbox输入，所以为字符型。
            object dbData = null;
            if (SearchParameters == null) SearchParameters = new DataParameterCollection();
            string temp = string.Empty;
            //			//空值返回
            //			if((searchvalue==null || searchvalue==string.Empty)&&operater!="=")
            //			{
            //				if(optType==2)return string.Empty;
            //				ViewState["sortString"]="";	
            //				return string.Empty;
            //			}
            if (searchType == SearchType.无附加查询 || searchType == SearchType.一次查询)
            {
                SearchCond = null;
                SearchParameters.Clear();
            }
            if (searchType == SearchType.一次查询 || searchType == SearchType.二次查询)
            {
                if (isGoodKeyName(FieldName) && isGoodOperater(operater))
                {
                    string fieldName = getSelectFeildName(FieldName);
                    SqlParameterDeclaration pKeyFieldName;
                    try
                    {
                        switch (valueType)
                        {
                            case "System.DateTime"://接受年月日形式
                                string tempsear = searchvalue.Trim();
                                string time1 = string.Empty;
                                string time2 = string.Empty;
                                if ((searchvalue == null || searchvalue == string.Empty) && operater == "=")
                                {
                                    string tempN = FieldName + getParameterExt();
                                    pKeyFieldName = new SqlParameterDeclaration(tempN);
                                    SearchCond += " and " + fieldName + "= " + DateTime.Parse(tempN);//pKeyFieldName.Generate();
                                    //									SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(tempN,DbType.DateTime));
                                    //									SearchParameters[SearchParameters.Count-1].Value=DBNull.Value;

                                    break;
                                }

                                if (tempsear.IndexOf(' ') > 0)
                                {
                                    time1 = tempsear.Substring(0, tempsear.IndexOf(' '));
                                    time2 = tempsear.Remove(0, tempsear.IndexOf(' '));
                                    if (time2 != null && time2 != string.Empty) time2 = time2.Trim();
                                }
                                else time1 = tempsear;
                                string time3 = string.Empty;
                                string Date1 = string.Empty;
                                if (time1 != null && time1 != string.Empty)
                                {
                                    if (time1.IndexOf(':') > 0 || (time1.Length < 3 && time2 != null && time2 != string.Empty)) { time3 = time1; Date1 = time2; }
                                    else
                                    { Date1 = time1; time3 = time2; }
                                }


                                int addtype = 2;
                                if (time3 == null || time3 == string.Empty)//只有日期
                                {
                                    if (Date1.IndexOf("年") >= 0)
                                    {
                                        addtype = 0;
                                        if (Date1.IndexOf("月") >= 0) addtype = 1;
                                        if (Date1.IndexOf("日") >= 0) addtype = 2;
                                    }
                                    else
                                    {
                                        int len = Date1.Length;
                                        if (len == 4) { addtype = 0; Date1 += "-01-01"; } //加年
                                        if (len == 7 || len == 6)
                                        {
                                            addtype = 1;
                                            int j = 0;
                                            for (j = 0; j < Date1.Length; j++)
                                            {
                                                if (Date1[j] < '0' || Date1[j] > '9') break;
                                            }
                                            string intval = Date1[j].ToString();
                                            if (j == 2) Date1 = Date1.Insert(j + 1, "01" + intval);
                                            else Date1 = Date1 + intval + "01";
                                        }//加月份
                                        if (len == 8 || len == 9) addtype = 2;//加日
                                    }
                                }
                                else
                                {
                                    if (time3.LastIndexOf(':') > 2) addtype = 5; //秒
                                    else if (time3.Length < 3)
                                    { addtype = 3; time3 = time3 + ":0"; } //小时
                                    else
                                        addtype = 4; //分钟
                                }
                                searchvalue = Date1 + " " + time3;
                                dbData = DateTime.Parse(searchvalue.Trim());
                                if (operater.ToLower() == "like" || operater == "=")
                                {
                                    DateTime dbData2;
                                    switch (addtype)
                                    {
                                        case 0:
                                            dbData2 = ((DateTime)dbData).AddYears(1);
                                            break;
                                        case 1:
                                            dbData2 = ((DateTime)dbData).AddMonths(1);
                                            break;
                                        case 2:
                                            dbData2 = ((DateTime)dbData).AddDays(1);
                                            break;
                                        case 3:
                                            dbData2 = ((DateTime)dbData).AddHours(1);
                                            break;
                                        case 4:
                                            dbData2 = ((DateTime)dbData).AddMinutes(1);
                                            break;
                                        case 5:
                                            dbData2 = ((DateTime)dbData).AddSeconds(1);
                                            break;
                                        default:
                                            dbData2 = ((DateTime)dbData).AddDays(1);
                                            break;
                                    }
                                    //使用between来替代= like.
                                    temp = FieldName + getParameterExt();
                                    string temp2 = FieldName + getParameterExt();
                                    pKeyFieldName = new SqlParameterDeclaration(temp);
                                    SqlParameterDeclaration pKeyFieldName2 = new SqlParameterDeclaration(temp2);
                                    SearchCond += " and " + fieldName + " >= " + DateTime.Parse(dbData.ToString())/*pKeyFieldName.Generate()*/+ " and " + fieldName + " < " + dbData2/*pKeyFieldName2.Generate()*/+ " ";
                                    //									SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp,dbData));
                                    //									SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp2,dbData2));

                                }
                                else // > <
                                {
                                    //									temp=FieldName+getParameterExt();									 
                                    //									pKeyFieldName=new SqlParameterDeclaration(temp);
                                    SearchCond += " and " + fieldName + " " + operater + " " + DateTime.Parse(dbData.ToString()) /*pKeyFieldName.Generate()*/+ " ";
                                    //									SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp,dbData));
                                }
                                break;
                            case "System.Int16":
                                goto case "System.Int64";
                            case "System.Int32":
                                goto case "System.Int64";
                            case "System.Int64":
                                if (operater.ToLower() == "like") operater = "=";
                                dbData = int.Parse(searchvalue);
                                SearchCond += " and " + fieldName + " " + operater + " " + searchvalue + " ";
                                break;
                            case "System.Decimal":
                                if (operater.ToLower() == "like") operater = "=";
                                dbData = Decimal.Parse(searchvalue);
                                SearchCond += " and " + fieldName + " " + operater + " " + searchvalue + " ";
                                break;
                            case "System.Boolean":
                                SearchCond += " and " + fieldName + " = " + bool.Parse(searchvalue);
                                break;

                            default:
                                if (searchvalue != null && searchvalue != string.Empty)
                                {
                                    temp = FieldName + getParameterExt();
                                    //如果是like，则另外处理searchvalue.
                                    if (operater.ToLower() == "like")
                                        searchvalue = getLikeValue(searchvalue);
                                    dbData = searchvalue;
                                    //									pKeyFieldName=new SqlParameterDeclaration(temp);
                                    SearchCond += " and " + fieldName + " " + operater + " '" + dbData/*pKeyFieldName.Generate()*/+ "' ";
                                    //									if (operater.ToLower()=="like")
                                    //										SearchCond+="escape '/' ";
                                    //									SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp,DbType.AnsiString));
                                    //									SearchParameters[SearchParameters.Count-1].Value=dbData;
                                }
                                else
                                {
                                    //如果是like，则另外处理searchvalue.
                                    if (operater.ToLower() == "like") break;
                                    //									temp=FieldName+getParameterExt();
                                    dbData = DBNull.Value;
                                    //									pKeyFieldName=new SqlParameterDeclaration(temp);
                                    SearchCond += " and " + fieldName + " " + operater + " " + dbData/*pKeyFieldName.Generate()*/+ " ";
                                    //									SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp,dbData));
                                }
                                break;
                        }
                        this.PageIndex = 0;
                        return null;
                    }
                    catch
                    {
                        switch (valueType)
                        {
                            case "System.DateTime"://接受年月日形式
                                return "输入格式不正确！应当输入日期！";
                                break;
                            case "System.Int16":
                                goto case "System.Int64";
                            case "System.Int32":
                                goto case "System.Int64";
                            case "System.Int64":
                                return "输入格式不正确！应当输入数字！";

                            case "System.Decimal":
                                return "输入格式不正确！应当输入数字！";

                            default:
                                return "输入格式不正确！";

                        }

                    }

                }
                return "操作错误！";
            }
            return null;
        }
        #endregion
        #region 数据绑定
        private void setPager()
        {
            
            this._aspager.RecordCount = _recordCount;
            this._aspager.PageSize = this.PageSize;
            this._aspager.PageButtonCount = 10;
            this._aspager.ShowInputBox = ShowInputBox.Always;
            this._aspager.HorizontalAlign = HorizontalAlign.Center;
            this._aspager.PageChanged += new PageChangedEventHandler(aspager_PageChanged);
        }
        /// <summary>
        /// 翻页动作
        /// </summary>
        /// <param name="src"></param>
        /// <param name="e"></param>
        void aspager_PageChanged(object src, PageChangedEventArgs e)
        {
            _CurrentPageIndex = e.NewPageIndex;
            this.PageIndex = e.NewPageIndex - 1;
            BindData(BindDataType.分页);
        }
        public void BindData(BindDataType bindType)
        {

            LogicDB ldb = new LogicDB();
            DataAccess da = micsunDB.CreateDataAccessor();
            IDataReader reader;
            int recordcount = 0;
            try
            {
                recordcount = int.Parse(da.ExecuteScalar(getCountSql(), SearchParameters).ToString());
            }
            catch (Exception ex)
            {
                string temp = ex.Message;
            }

            //this.VirtualItemCount = recordcount;
            //
            this._recordCount = recordcount;

            if (this.AllowCustomPaging)
            {
                _aspager.RecordCount =  recordcount;
                if (bindType == BindDataType.搜索位置)
                {
                    int i = 0;
                    //重新计算分页
                    if (RecordPosition >= 0)
                    {
                        if (RecordPosition >= recordcount) RecordPosition = recordcount - 1;
                        SingleSelectPostion = RecordPosition % this.PageSize;
                        this.PageIndex = RecordPosition / this.PageSize;
                        
                    }
                    else
                    {
                        if (KeyFeildNameList != null && KeyFeildNameList != string.Empty)
                        {
                            if (SearchParameters != null)
                                for (i = 0; i < SearchParameters.Count; i++)
                                    Parameters.Add(SearchParameters[i]);
                            IDataReader treader = da.ExecuteReader(getPositionSql(), Parameters);
                            if (treader.Read())
                            {
                                i = treader.GetInt32(0) - 1;
                                if (i < 0) i = 0;
                                SingleSelectPostion = i % this.PageSize;
                                this._aspager.CurrentPageIndex = this.PageIndex = i / this.PageSize;
                            }
                        }
                    }
                }
                
                reader = micsunDB.CreateDataAccessor().ExecuteReader(getPagerSql(), SearchParameters);
            }
            else
            {

                reader = da.ExecuteReader(getOrinSql(), SearchParameters);
            }
            SchemaTable = reader.GetSchemaTable();
            this.DataSource = reader;

            //int pageCount = this.VirtualItemCount / this.PageSize + ((this.VirtualItemCount % this.PageSize > 0) ? 1 : 0) - 1;
            //if (pageCount < 0) pageCount = 0;
            //this.PageIndex = (this.CurrentPageIndex > pageCount ? pageCount : this.CurrentPageIndex);
            try
            {
                this.DataBind();
            }
            catch
            {
#if DEBUG
                throw;
#endif
            }
            reader.Close();
        }

        protected override void OnRowDataBound(GridViewRowEventArgs e)
        {
            base.OnRowDataBound(e);
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                try
                {

                    int cellscount = e.Row.Cells.Count;
                    e.Row.Cells.Clear();
                    e.Row.Cells.Add(new TableCell());
                    e.Row.Cells[0].ColumnSpan = cellscount;
                    _aspager.CurrentPageIndex = _CurrentPageIndex;
                    setPager();
                    e.Row.Cells[0].Controls.Add(_aspager);
                }
                catch { }
            }
            
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string keyvalue = string.Empty;
                int i = 0;

                for (i = 0; i < KeyIDPosition.Length; i++)
                {
                    keyvalue += e.Row.Cells[KeyIDPosition[i]].Text + "|";
                }
                for (i = 1; i < e.Row.Cells.Count; i++)
                {
                    if (!e.Row.Cells[i].Text.Equals("&nbsp;") && !e.Row.Cells[i].HasControls()) e.Row.Cells[i].Text = HttpUtility.HtmlEncode(e.Row.Cells[i].Text);
                }

                keyvalue += (this.PageSize * this.PageIndex + e.Row.RowIndex);
                if (this.SelectType != SelectType.MultiSelect)
                {
                    if (e.Row.RowIndex == SingleSelectPostion)
                    {
                        if (e.Row.FindControl("TempLabel") != null)
                        {
                            ((Label)e.Row.FindControl("TempLabel")).Text = "<INPUT type=" + getCheckBoxString() + " name='" + KeyIDName + "' id='" + KeyIDName + "' checked value='" + keyvalue + "'>";
                            KeyIDValue = keyvalue;
                        }
                    }
                    else
                    {
                        if (e.Row.FindControl("TempLabel") != null)
                        {
                            ((Label)e.Row.FindControl("TempLabel")).Text = "<INPUT type=" + getCheckBoxString() + " name='" + KeyIDName + "' id='" + KeyIDName + "' value='" + keyvalue + "'>";
                        }
                    }
                }
                else
                {
                    if (e.Row.FindControl("TempLabel") != null)
                    {
                        ((Label)e.Row.FindControl("TempLabel")).Text = "<INPUT type=" + getCheckBoxString() + " name='" + KeyIDName + "' id='" + KeyIDName + "' value='" + keyvalue + "' onclick=\"if(!this.checked)document.all." + this.KeyIDName + "[0].checked=false;" + " \">";
                    }
                }
                e.Row.Attributes.Add("onmouseover", "this.style.cursor = 'hand';currentcolor=this.style.backgroundColor;this.style.backgroundColor='#d3d3d3'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor");
                //判断是否在前台添加了单击事件
                if (e.Row.Attributes["onclick"] == null)
                    e.Row.Attributes.Add("onclick", "this.cells(0).children(0).children(0).click();");
                else
                    e.Row.Attributes["onclick"] = "this.cells(0).children(0).children(0).click();" + e.Row.Attributes["onclick"];
            }
        }
        protected override void OnRowCreated(GridViewRowEventArgs e)
        {
            base.OnRowCreated(e);
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                try
                {

                    int cellscount = e.Row.Cells.Count;
                    e.Row.Cells.Clear();
                    e.Row.Cells.Add(new TableCell());
                    e.Row.Cells[0].ColumnSpan = cellscount;
                    _aspager.CurrentPageIndex = _CurrentPageIndex;
                    setPager();
                    e.Row.Cells[0].Controls.Add(_aspager);
                }
                catch { }
            }
#region 自定义排序
            //绑定头
           /* if (e.Row.RowType == DataControlRowType.Header)
            {
                if (this.SelectType == SelectType.MultiSelect)
                    e.Row.Cells[0].Text = "<INPUT type=" + getCheckBoxString() + " name='" + KeyIDName + "' id='" + KeyIDName + "'  value=ALL onClick=\"AllBoxClick()\">全选";

                //增加排序按钮
                for (int j = 1; j < e.Row.Cells.Count; j++)
                {
                    string opField = string.Empty;
                    try
                    {
                        opField = ((BoundField)this.Columns[j]).DataField;
                    }
                    catch
                    {
                        continue;
                    }
                    int currOrderType = 0;//当前的排序类型

                    if (_orderList != null && _orderList.IndexOf(opField) >= 0)
                    {
                        int startpos = _orderList.IndexOf(opField);
                        int endpos = startpos + opField.Length;
                        bool goodbegin = false;
                        if (startpos == 0) goodbegin = true;
                        if (startpos > 0 && (_orderList[startpos - 1] == ' ' || _orderList[startpos - 1] == ',')) goodbegin = true;
                        bool goodend = false;
                        if (endpos == _orderList.Length) goodend = true;
                        if (endpos < _orderList.Length && (_orderList[endpos] == ' ' || _orderList[endpos] == ',')) goodend = true;

                        if (goodbegin && goodend)
                        {
                            string temp = _orderList.Substring(_orderList.IndexOf(opField) + opField.Length, _orderList.Length - _orderList.IndexOf(opField) - opField.Length);
                            if (temp.Trim().ToUpper().StartsWith("D")) currOrderType = 2;//desc
                            else currOrderType = 1;//asc
                        }
                    }
                    if (this.Columns[j].Visible)
                    {
                        string OrderBy = "<table cellpadding=0 cellspacing=0 border=0>	<tr><td rowspan=3 nowrap><font color=\"#ffffff\" >" + e.Row.Cells[j].Text +
                            "<font></td><td valign=top height =1>";
                        if (currOrderType == 1)
                            OrderBy += "<font face=\"webdings\" color=\"red\" size=1>5</font>";//"<img width=10 src='" + GetUrlRoot() + "images/default/arrowupred.gif' >";
                        else
                            OrderBy += "<font face=\"webdings\" size=1 style='CURSOR: hand' onclick=" + Page.ClientScript.GetPostBackEventReference(this, "asc|" + j) + ">5</font>";//"<img src='" + GetUrlRoot() + "images/default/arrowup.gif' style='CURSOR: hand' onclick=" + Page.GetPostBackEventReference(this, "asc|" + j) + ">";
                        OrderBy += "</td>	</tr><tr><td valign=center>";
                        if (currOrderType == 0)
                            OrderBy += "<font  color=\"red\">-</font>";//"<img src='" + GetUrlRoot() + "images/default/arrowcancelred.gif' >";
                        else
                            OrderBy += "<font   style='CURSOR: hand' onclick=" + Page.ClientScript.GetPostBackEventReference(this, "cancelorder|" + j) + ">-</font>";//"<img src='" + GetUrlRoot() + "images/default/arrowcancel.gif' style='CURSOR: hand' onclick=" + Page.GetPostBackEventReference(this, "cancelorder|" + j) + ">";
                        OrderBy += "</td></tr><tr><td valign=bottom>";
                        if (currOrderType == 2)
                            OrderBy += "<font face=\"webdings\" color=\"red\" size=1>6</font>";//"<img src='" + GetUrlRoot() + "images/default/arrowdownred.gif' >";
                        else
                            OrderBy += "<font face=\"webdings\" size=1 style='CURSOR: hand' onclick=" + Page.ClientScript.GetPostBackEventReference(this, "asc|" + j) + ">6</font>"; //"<img src='" + GetUrlRoot() + "images/default/arrowdown.gif' style='CURSOR: hand' onclick=" + Page.GetPostBackEventReference(this, "desc|" + j) + ">";
                        OrderBy += "</td></tr></table>";
                        e.Row.Cells[j].Text = OrderBy;
                    }
                }

            }*/
#endregion     

        }

        #endregion
        #region 配套方法
        bool isGoodKeyName(string KeyName)
        {
            if (KeyName == string.Empty) return false;
            if (KeyName.Trim().IndexOf(" ") >= 0) return false;//不能包含空格
            if (KeyName.IndexOf("%") >= 0) return false;//不能包含%
            if (KeyName.IndexOf("'") >= 0) return false;//不能包含单引号
            if (KeyName.IndexOf("=") >= 0) return false;//不能包含=号
            //检查是否在selectLis中
            //			string tempstr= (VSelectList==string.Empty)?SelectList:VSelectList;
            //			if(tempstr.IndexOf(KeyName)<0)return false;
            return true;
        }
        string getSelectFeildName(string fieldName)
        {

            if (fieldName.IndexOf('.') > 0) return fieldName;//已经带了表名
            if (fieldName.IndexOf('(') > 0) return fieldName;//已经指定是计算字段
            if (_selectList.Trim() == "*") return fieldName;//单表非计算字段

            string FieldName = fieldName.ToLower();
            string tempSelectList = _selectList.ToLower();
            tempSelectList = tempSelectList.Replace(" ,", ",");
            if (tempSelectList == null || tempSelectList == string.Empty) return FieldName;

            //if(_tableList.Split(',').Length==1 && _tableList.ToLower().IndexOf("join")<0  )return FieldName;//单表

            int start, end;
            start = 0;
            end = 0;
            tempSelectList = tempSelectList.Trim();
            if (tempSelectList.StartsWith("distinct ")) tempSelectList = tempSelectList.Remove(0, 9);
            if (tempSelectList.IndexOf(FieldName) < 0)
            {
                //不在列表中				
                end = tempSelectList.IndexOf("*");//属于*所在的表
                if (end < 0) return fieldName;//可能为非重复字段
                //猜测他在* 中
                int two = tempSelectList.IndexOf("*", end);
                if (two >= 0) return fieldName;//多个*则则放弃
                tempSelectList = tempSelectList.Substring(0, end);
                start = tempSelectList.LastIndexOf(',') + 1;
                return tempSelectList.Substring(start, end - start) + fieldName;
            }
            else
            {
                tempSelectList += ",";
                ArrayList al = splitCommaList(tempSelectList);
                for (int i = 0; i < al.Count; i++)
                {
                    string temp = al[i].ToString().Trim();
                    if (temp.EndsWith(FieldName))
                    {
                        temp = temp.TrimEnd(FieldName.ToCharArray());
                        if (temp != null && temp != string.Empty)//前面有内容
                        {
                            if (al[i].ToString().Trim().IndexOf(' ') < 0 && al[i].ToString().Trim().IndexOf(')') < 0)//非计算字段
                                return al[i].ToString().Trim();
                            else //计算字段
                            {
                                string cutfieldname = al[i].ToString().Trim().Remove(al[i].ToString().Trim().Length - FieldName.Length, FieldName.Length).Trim();
                                if (cutfieldname.LastIndexOf(" as") == cutfieldname.Length - 3) cutfieldname = cutfieldname.Remove(cutfieldname.Length - 3, 3);
                                return "(" + cutfieldname.ToUpper() + ")";
                            }
                        }
                    }
                }
                return FieldName;
            }
        }

        bool isGoodOperater(string Operater)
        {
            if (Operater == string.Empty) return false;
            if (Operater.Equals("=")) return true;
            if (Operater.Equals(">")) return true;
            if (Operater.Equals("<")) return true;
            if (Operater.Equals("<=")) return true;
            if (Operater.Equals("=>")) return true;
            if (Operater.ToLower().Equals("like")) return true;
            return false;
        }
        /// <summary>
        /// 替换/ % _ ,为escape子句做准备
        /// </summary>
        /// <param name="likevalue"></param>
        /// <returns></returns>
        string getLikeValue(string likevalue)
        {
            string tempStr = string.Empty;
            tempStr = likevalue.Replace("/", "//").Replace("%", "/%").Replace("_", "/_");
            return "%" + tempStr + "%";
        }

        /// <summary>
        /// 分解逗号表达式
        /// </summary>
        /// <param name="CommaList"></param>
        /// <returns></returns>
        ArrayList splitCommaList(string CommaList)
        {
            ArrayList al = new ArrayList();
            int i = 0;
            int j = 0;
            while (CommaList != string.Empty)
            {
                for (i = 0; i < CommaList.Length; i++)
                {
                    if (CommaList[i] == ')') j--;
                    if (CommaList[i] == '(') j++;
                    if (CommaList[i] == ',' && j == 0)
                    {
                        al.Add(CommaList.Substring(0, i));
                        CommaList = CommaList.Substring(i + 1, CommaList.Length - i - 1);
                        break;
                    }
                }
            }
            return al;
        }
        //获取参数后缀
        static long ParameterNumber = 0;
        string getParameterExt()
        {
            ParameterNumber++;
            return "A" + ParameterNumber;
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            try
            {
                SearchCond = ViewState["SearchCond"].ToString();
            }
            catch { SearchCond = ""; }
            SearchParameters = (DataParameterCollection)ViewState["SearchParameters"];
            if (SearchParameters != null)
            {
                for (int i = 0; i < SearchParameters.Count; i++)
                {
                    SearchParameters[i].Value = ViewState[SearchParameters[i].ParameterName];
                }
            }
            else
            {
                SearchParameters = new DataParameterCollection();
            }

            try
            {
                KeyIDName = ViewState["KeyIDName"].ToString();
            }
            catch { KeyIDName = ""; }
            try
            {
                _vselectList = ViewState["_vselectList"].ToString();
            }
            catch { _vselectList = ""; }
            try
            {
                _selectList = ViewState["_selectList"].ToString();
            }
            catch { _selectList = ""; }
            try
            {
                _tableList = ViewState["_tableList"].ToString();
            }
            catch { _tableList = ""; }
            try
            {
                _whereList = ViewState["_whereList"].ToString();
            }
            catch { _whereList = ""; }
            try
            {
                _groupList = ViewState["_groupList"].ToString();
            }
            catch { _groupList = ""; }
            try
            {
                _havingList = ViewState["_havingList"].ToString();
            }
            catch { _havingList = ""; }
            try
            {
                _orderList = ViewState["_orderList"].ToString();
            }
            catch { _orderList = ""; }
            try
            {
                SelectType = (SelectType)ViewState["SelectType"];
            }
            catch { SelectType = SelectType.SingleSelect; }
            try
            {
                KeyIDPosition = (int[])ViewState["KeyIDPosition"];
            }
            catch
            {
                KeyIDPosition = new int[] { 1 };
            }
            try
            {
                KeyIDValue = ViewState["KeyIDValue"].ToString();
            }
            catch { KeyIDValue = ""; }

        }
        protected override object SaveViewState()
        {
            ViewState["SearchCond"] = SearchCond;
            ViewState["SearchParameters"] = SearchParameters;
            if (SearchParameters != null)
            {
                for (int i = 0; i < SearchParameters.Count; i++)
                {
                    ViewState[SearchParameters[i].ParameterName] = SearchParameters[i].Value;
                }
            }
            ViewState["KeyIDName"] = KeyIDName;
            ViewState["_vselectList"] = _vselectList;
            ViewState["_selectList"] = _selectList;
            ViewState["_tableList"] = _tableList;
            ViewState["_whereList"] = _whereList;
            ViewState["_groupList"] = _groupList;
            ViewState["_havingList"] = _havingList;
            ViewState["_orderList"] = _orderList;
            ViewState["SelectType"] = SelectType;
            ViewState["KeyIDPosition"] = KeyIDPosition;
            ViewState["KeyIDValue"] = KeyIDValue;
            return base.SaveViewState();
        }
        
        
        

        private string GetUrlRoot()
        {

            return ApplicationBase.GetUrlRoot();
        }
        #endregion
    }
    public class GridViewPlus2 : System.Web.UI.WebControls.DataGrid, IPostBackEventHandler
    {
        public GridViewPlus2()
            : base()
        {
        }
        HtmlButton b;
        protected System.Web.UI.WebControls.TextBox TxtJmp = new TextBox();
        private DataParameterCollection Parameters = new DataParameterCollection();//定位参数，每次搜索时会更新
        public DataTable SchemaTable;
        public string KeyIDName;
        public int[] KeyIDPosition = new int[] { 1 };

        public SelectType SelectType;

        private string getCheckBoxString()
        {
            if (this.SelectType == SelectType.MultiSelect)
                return "CheckBox";
            else
                return "Radio";
        }
        #region sql语句生成器
        string _vselectList;
        public string VSelectList
        {
            get { return _vselectList; }
            set { _vselectList = value; }
        }
        string _selectList;
        public string SelectList
        {
            get { return _selectList; }
            set { _selectList = value; }
        }
        string _tableList;
        public string TableList
        {
            get { return _tableList; }
            set { _tableList = value; }
        }
        string _whereList;
        public string WhereList
        {
            get
            {
                string temp = _whereList + SearchCond;
                if (temp != null)
                {
                    if (temp.StartsWith(" and ")) temp = temp.Remove(0, 5);
                    if (temp.Trim() == string.Empty)
                        return null;
                }
                return temp;
            }
            set { _whereList = value; }
        }
        string _groupList;
        public string GroupList
        {
            get { return _groupList; }
            set { _groupList = value; }
        }
        string _havingList;
        public string HavingList
        {
            get { return _havingList; }
            set { _havingList = value; }
        }
        string _orderList;
        public string OrderList
        {
            get { return _orderList; }
            set { _orderList = value; }
        }
        public string getCountSql()
        {
            string temp = string.Empty;
            if (_selectList.TrimStart(' ').ToLower().StartsWith("distinct "))
            {//temp= "select count("+_selectList+") from "+_tableList ;
                temp = "select " + _selectList + " from " + _tableList;
                temp += (WhereList == null || WhereList == string.Empty) ? null : (" where " + WhereList);
                temp += (_groupList == null || _groupList == string.Empty) ? null : (" group by " + _groupList);
                temp += (_havingList == null || _havingList == string.Empty) ? null : (" HAVING  " + _havingList);
                //temp+=(_orderList==null || _orderList==string.Empty)?null:(" order by "+_orderList);
                temp = "select count(*) from (" + temp + ")";
            }
            else
            {
                temp = "select count(*) from " + _tableList;
                temp += (WhereList == null || WhereList == string.Empty) ? null : (" where " + WhereList);
                temp += (_groupList == null || _groupList == string.Empty) ? null : (" group by " + _groupList);
                temp += (_havingList == null || _havingList == string.Empty) ? null : (" HAVING  " + _havingList);
                //temp+=(_orderList==null || _orderList==string.Empty)?null:(" order by "+_orderList);
                if (_groupList != null && _groupList != string.Empty)
                    temp = "select count(*) from (" + temp + ")";
            }
            return temp;
        }
        public string getOrinSql()
        {
            string temp = "select " + ((_selectList == null || _selectList == string.Empty) ? " * " :  _selectList) + " from " + _tableList;
            temp += (WhereList == null || WhereList == string.Empty) ? null : (" where " + WhereList);
            temp += (_groupList == null || _groupList == string.Empty) ? null : (" group by " + _groupList);
            temp += (_havingList == null || _havingList == string.Empty) ? null : (" HAVING  " + _havingList);
            temp += (_orderList == null || _orderList == string.Empty) ? null : (" order by " + _orderList);
            return temp;
        }
        //public string getPagerSql()
        //{
        //    if (this.CurrentPageIndex < 0) this.CurrentPageIndex = 0;
        //    StringBuilder builder = new StringBuilder();
        //    builder.Append("select ")
        //        .Append(((_vselectList == null || _vselectList == string.Empty) ? " * " : _vselectList))
        //        .Append(" from ")
        //        .Append("(select row_number() over(order by getdate()) as myrownum,tt.* from (")
        //        .Append(getOrinSql())
        //        .Append(") tt where  rownum<=" + this.PageSize * (this.CurrentPageIndex + 1))
        //        .Append(") tt1 where myrownum>" + this.PageSize * this.CurrentPageIndex);
        //    return builder.ToString();
        //}
        public string getPagerSql()
        {
            if (this.CurrentPageIndex < 0) this.CurrentPageIndex = 0;
            StringBuilder builder = new StringBuilder();
            builder.Append("select ")
                .Append(((_vselectList == null || _vselectList == string.Empty) ? " * " : _vselectList))
                .Append(" from ")
                .Append("(select tt.* from (")
                .Append(getOrinSql())
                .Append(") tt" )
                .Append(") tt1 limit " + this.PageSize * this.CurrentPageIndex +","+ this.PageSize );//+ 
            return builder.ToString();
        }
        /// <summary>
        /// 获取keyID位置的sql语句
        /// </summary>
        /// <returns></returns>
        public string getPositionSql()
        {
            if (this.CurrentPageIndex < 0) this.CurrentPageIndex = 0;
            StringBuilder builder = new StringBuilder();
            builder.Append("set @myNum:=0;select  myrownum")//myrownum_-->*
                 
                .Append(" from ")
                .Append("(select (@myNum:=@myNum+1) as myrownum,tt.*")//keyfileName
                .Append(" from (")
                .Append(getOrinSql())
                .Append(") tt ")
                .Append(") tt1 where ")
                .Append(KeyFieldCondList.Substring(4) )
                .Append(" limit " + this.PageSize * this.CurrentPageIndex + "," + this.PageSize);
            return builder.ToString();
        }
        public void AddCondAnd(string cond)
        {
            if (WhereList == string.Empty)
                WhereList = cond;
            else
                WhereList += " and " + cond;
        }

        public void AddCondOr(string cond)
        {
            if (WhereList == string.Empty)
                WhereList = cond;
            else
                WhereList = " (" + WhereList + ") " + " or " + cond;
        }
        #endregion
        #region 自定义分页
        protected override void OnItemCreated(DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Pager)
            {
                e.Item.Cells[0].Text = " ";//关键：：屏蔽掉缺省的按钮。
                buildPagerCell(e.Item.Cells[0]);
            }

            base.OnItemCreated(e);
        }
        #region 分页外观
        TableCell buildPagerCell(TableCell pagerCell)
        {

            int pageCount = this.PageCount;
            int pageButtonCount = this.PagerStyle.PageButtonCount;
            int currentPageIndex = this.CurrentPageIndex;
            int i;
            int startCount, endCount;
            startCount = currentPageIndex / pageButtonCount * pageButtonCount;
            endCount = startCount + pageButtonCount;
            //((startCount+pageButtonCount)>pageCount)?pageCount:startCount+pageButtonCount;
            //右移一点
            Label lt = new Label();
            lt.Text = "&nbsp;";
            pagerCell.Controls.Add(lt);
            if (pageCount == 1) return pagerCell;
            pagerCell.Controls.Add(CreateLinkButton(0, "首页"));
            pagerCell.Controls.Add(CreateLinkButton(startCount - 1, "前翻"));
            pagerCell.Controls.Add(CreateLinkButton((currentPageIndex - 1 < 0) ? 0 : (currentPageIndex - 1), "上一页"));
            //数字按钮
            for (i = startCount; i < endCount; i++)
            {
                pagerCell.Controls.Add(CreateLinkButton(i, (i + 1).ToString()));
            }
            pagerCell.Controls.Add(CreateLinkButton((currentPageIndex + 1 == pageCount) ? pageCount - 1 : (currentPageIndex + 1), "下一页"));
            pagerCell.Controls.Add(CreateLinkButton(endCount, "下翻"));
            pagerCell.Controls.Add(CreateLinkButton(pageCount - 1, "末页"));
            //创建go button;
            //文本框
            TxtJmp.Width = new Unit("30px");
            //TxtJmp.Height = new Unit("20px");
            pagerCell.Controls.Add(TxtJmp);
            HtmlButton b = new HtmlButton();
            b.ID = "pageSizeBtn";
            //TxtJmp.Attributes.Add("onkeydown", "if(event.keyCode==13){ ctl00_ContentPlaceHolderBody_MtnDG_ctl05_pageSizeBtn.click();return false;}");//
            
            b.Attributes.Add("style", "width:30 px;");
            b.InnerText = "Go";
            b.ServerClick += new EventHandler(Pager_ServerClick);
            b.Attributes.Add("onmouseover", "this.style.cursor='hand';");
            pagerCell.Controls.Add(b);
            Label lbltotCount = new Label();
            lbltotCount.Text = "<font size=2 color=#ff0000>记录总数：" + this.VirtualItemCount.ToString() + "&nbsp;&nbsp;总页数：" + this.PageCount + "&nbsp;&nbsp;每页记录数：" + this.PageSize + "</font>";
            lbltotCount.ID = "lbltotCount";
            pagerCell.Controls.Add(lbltotCount);
            return pagerCell;
        }
        //创建一个新的link
        private Control CreateLinkButton(int CurrPage, string innerHtml)
        {
            HtmlAnchor a = new HtmlAnchor();
            a.InnerHtml = " " + innerHtml + " ";
            a.EnableViewState = false;
            //重要，不要改动这两句
            if (CurrPage != this.CurrentPageIndex && CurrPage >= 0 && CurrPage < this.PageCount)
            {
                a.ServerClick += new EventHandler(Pager_ServerClick);
                a.Attributes.Add("CurrPage", CurrPage.ToString());
            }
            else
            {
                try
                {
                    int i = int.Parse(innerHtml);
                    a.InnerHtml = "<b><font size=2 color=#ff0000> " + " " + innerHtml + "</font></b> ";
                    if (i > this.PageCount) a.Visible = false;
                }
                catch
                {
                    a.InnerHtml = "<font size=2 > " + " " + innerHtml + "</font> ";
                    if (innerHtml.Equals("前翻") || innerHtml.Equals("下翻")) if (this.PageCount < this.PagerStyle.PageButtonCount) a.Visible = false;
                }

                a.Disabled = true;
            }
            return (Control)a;
        }



        #endregion
        /// <summary>
        /// 处理分页事件
        /// </summary>
        /// <param name="sender"> </param>
        /// <param name="e"></param>
        private void Pager_ServerClick(object sender, EventArgs e)
        {
            //计算新页位置
            int currPage = 1;

            Type type = sender.GetType();
            switch (type.Name)
            {
                //go 按钮
                case "HtmlButton":
                    try
                    {
                        currPage = int.Parse(TxtJmp.Text) - 1;
                    }
                    catch
                    {
                        currPage = 0;
                    }
                    if (currPage <= 0) TxtJmp.Text = "1";
                    if (currPage >= this.PageCount) TxtJmp.Text = this.PageCount.ToString();
                    break;
                case "HtmlAnchor":
                    try
                    {
                        currPage = int.Parse(((HtmlAnchor)sender).Attributes["CurrPage"].ToString());
                    }
                    catch
                    {
                        currPage = 0;
                    }

                    break;
                default:
                    currPage = 0;
                    break;
            }
            //检查新页次的合理性
            if (currPage < 0) currPage = 0;
            if (currPage >= this.PageCount) currPage = this.PageCount - 1;

            //重新分页
            this.CurrentPageIndex = currPage;
            BindData(BindDataType.分页);
        }
        #endregion
        #region 记录定位
        private string KeyFieldCondList;
        private string KeyFeildNameList;
        public int RecordPosition = -1;
        public string KeyIDValue;
        private int SingleSelectPostion;
        //记录定位必须知道key和keyvalue
        /// <summary>
        /// 生成KeyFieldList,KeyFieldCondList,Parameters
        /// </summary>
        /// <param name="KeyFieldName"></param>
        /// <param name="KeyFieldVale"></param>
        public void AddFindField(string KeyFieldName, object KeyFieldValue)
        {
            if (isGoodKeyName(KeyFieldName) && KeyFieldValue != null)
            {
                //不允许全为空格。
                if (KeyFieldValue.ToString().Trim() == string.Empty)
                {
                    return;
                }
                KeyFeildNameList += "," + KeyFieldName;
                //KeyFeildSumList+="||"+ trim(to_char(funid))||grpid
                string temp = KeyFieldName + getParameterExt();
                SqlParameterDeclaration pKeyFieldName = new SqlParameterDeclaration(temp);
                KeyFieldCondList += " and " + KeyFieldName + "=" + pKeyFieldName.Generate();
                Parameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp, KeyFieldValue));
            }
        }
        //用于没有翻页的时候定位，只适用于单选，不刷新的情况。
        public void RegisterFindScript()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append("<script language=\"javascript\">\r\n")
                .Append("function _Set" + this.UniqueID + "KeyID() \r\n")
                .Append("{")
                .Append("var oObject = document.all.item('" + KeyIDName + "');")
                .Append("  if (oObject != null){")
                .Append("if (oObject.length != null){")
                .Append("for (i = 0; i < oObject.length; i++){")
                .Append("if(oObject(i).value=='" + KeyIDValue + "')oObject(i).checked=true;")
                .Append("}")
                .Append("}")
                .Append("else")
                .Append("{")
                .Append("oObject.checked=true;")
                .Append("}")
                .Append("}")
                .Append("}\r\n")
                .Append("_Set" + this.UniqueID + "KeyID();\r\n")
                .Append("</script>");
            Page.RegisterStartupScript(this.UniqueID + "__messageHandler1", builder.ToString());
        }
        #endregion
        #region  查询和二次查询
        private string SearchCond;
        private DataParameterCollection SearchParameters;
        /// <summary>
        /// 查询和二次查询条件
        /// </summary>
        public string AddSearchCond(string FieldName, string operater, string searchvalue, string valueType, SearchType searchType)
        {
            //因为searchvalue是从textbox输入，所以为字符型。
            object dbData = null;
            if (SearchParameters == null) SearchParameters = new DataParameterCollection();
            string temp = string.Empty;
            //			//空值返回
            //			if((searchvalue==null || searchvalue==string.Empty)&&operater!="=")
            //			{
            //				if(optType==2)return string.Empty;
            //				ViewState["sortString"]="";	
            //				return string.Empty;
            //			}
            if (searchType == SearchType.无附加查询 || searchType == SearchType.一次查询)
            {
                SearchCond = null;
                SearchParameters.Clear();
            }
            if (searchType == SearchType.一次查询 || searchType == SearchType.二次查询)
            {
                if (isGoodKeyName(FieldName) && isGoodOperater(operater))
                {
                    string fieldName = getSelectFeildName(FieldName);
                    SqlParameterDeclaration pKeyFieldName;
                    try
                    {
                        switch (valueType)
                        {
                            case "System.DateTime"://接受年月日形式
                                string tempsear = searchvalue.Trim();
                                string time1 = string.Empty;
                                string time2 = string.Empty;
                                if ((searchvalue == null || searchvalue == string.Empty) && operater == "=")
                                {
                                    string tempN = FieldName + getParameterExt();
                                    pKeyFieldName = new SqlParameterDeclaration(tempN);
                                    SearchCond += " and " + fieldName + "= " + pKeyFieldName.Generate();
                                    SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(tempN, DbType.DateTime));
                                    SearchParameters[SearchParameters.Count - 1].Value = DBNull.Value;

                                    break;
                                }

                                if (tempsear.IndexOf(' ') > 0)
                                {
                                    time1 = tempsear.Substring(0, tempsear.IndexOf(' '));
                                    time2 = tempsear.Remove(0, tempsear.IndexOf(' '));
                                    if (time2 != null && time2 != string.Empty) time2 = time2.Trim();
                                }
                                else time1 = tempsear;
                                string time3 = string.Empty;
                                string Date1 = string.Empty;
                                if (time1 != null && time1 != string.Empty)
                                {
                                    if (time1.IndexOf(':') > 0 || (time1.Length < 3 && time2 != null && time2 != string.Empty)) { time3 = time1; Date1 = time2; }
                                    else
                                    { Date1 = time1; time3 = time2; }
                                }


                                int addtype = 2;
                                if (time3 == null || time3 == string.Empty)//只有日期
                                {
                                    if (Date1.IndexOf("年") >= 0)
                                    {
                                        addtype = 0;
                                        if (Date1.IndexOf("月") >= 0) addtype = 1;
                                        if (Date1.IndexOf("日") >= 0) addtype = 2;
                                    }
                                    else
                                    {
                                        int len = Date1.Length;
                                        if (len == 4) { addtype = 0; Date1 += "-01-01"; } //加年
                                        if (len == 7 || len == 6)
                                        {
                                            addtype = 1;
                                            int j = 0;
                                            for (j = 0; j < Date1.Length; j++)
                                            {
                                                if (Date1[j] < '0' || Date1[j] > '9') break;
                                            }
                                            string intval = Date1[j].ToString();
                                            if (j == 2) Date1 = Date1.Insert(j + 1, "01" + intval);
                                            else Date1 = Date1 + intval + "01";
                                        }//加月份
                                        if (len == 8 || len == 9) addtype = 2;//加日
                                    }
                                }
                                else
                                {
                                    if (time3.LastIndexOf(':') > 2) addtype = 5; //秒
                                    else if (time3.Length < 3)
                                    { addtype = 3; time3 = time3 + ":0"; } //小时
                                    else
                                        addtype = 4; //分钟
                                }
                                searchvalue = Date1 + " " + time3;
                                dbData = DateTime.Parse(searchvalue.Trim());
                                if (operater.ToLower() == "like" || operater == "=")
                                {
                                    DateTime dbData2;
                                    switch (addtype)
                                    {
                                        case 0:
                                            dbData2 = ((DateTime)dbData).AddYears(1);
                                            break;
                                        case 1:
                                            dbData2 = ((DateTime)dbData).AddMonths(1);
                                            break;
                                        case 2:
                                            dbData2 = ((DateTime)dbData).AddDays(1);
                                            break;
                                        case 3:
                                            dbData2 = ((DateTime)dbData).AddHours(1);
                                            break;
                                        case 4:
                                            dbData2 = ((DateTime)dbData).AddMinutes(1);
                                            break;
                                        case 5:
                                            dbData2 = ((DateTime)dbData).AddSeconds(1);
                                            break;
                                        default:
                                            dbData2 = ((DateTime)dbData).AddDays(1);
                                            break;
                                    }
                                    //使用between来替代= like.
                                    temp = FieldName + getParameterExt();
                                    string temp2 = FieldName + getParameterExt();
                                    pKeyFieldName = new SqlParameterDeclaration(temp);
                                    SqlParameterDeclaration pKeyFieldName2 = new SqlParameterDeclaration(temp2);
                                    SearchCond += " and " + fieldName + " >= " + pKeyFieldName.Generate() + " and " + fieldName + " < " + pKeyFieldName2.Generate() + " ";
                                    SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp, dbData));
                                    SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp2, dbData2));

                                }
                                else // > <
                                {
                                    temp = FieldName + getParameterExt();
                                    pKeyFieldName = new SqlParameterDeclaration(temp);
                                    SearchCond += " and " + fieldName + " " + operater + " " + pKeyFieldName.Generate() + " ";
                                    SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp, dbData));
                                }
                                break;
                            case "System.Int16":
                                goto case "System.Int64";
                            case "System.Int32":
                                goto case "System.Int64";
                            case "System.Int64":
                                if (operater.ToLower() == "like") operater = "=";
                                dbData = int.Parse(searchvalue);
                                SearchCond += " and " + fieldName + " " + operater + " " + searchvalue + " ";
                                break;
                            case "System.Decimal":
                                if (operater.ToLower() == "like") operater = "=";
                                dbData = Decimal.Parse(searchvalue);
                                SearchCond += " and " + fieldName + " " + operater + " " + searchvalue + " ";
                                break;
                            default:
                                if (searchvalue != null && searchvalue != string.Empty)
                                {
                                    temp = FieldName + getParameterExt();
                                    //如果是like，则另外处理searchvalue.
                                    if (operater.ToLower() == "like")
                                        searchvalue = getLikeValue(searchvalue);
                                    dbData = searchvalue;
                                    pKeyFieldName = new SqlParameterDeclaration(temp);
                                    SearchCond += " and " + fieldName + " " + operater + " " + pKeyFieldName.Generate() + " ";
                                    if (operater.ToLower() == "like")
                                        SearchCond += "escape '/' ";
                                    SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp, DbType.AnsiString));
                                    SearchParameters[SearchParameters.Count - 1].Value = dbData;
                                }
                                else
                                {
                                    //如果是like，则另外处理searchvalue.
                                    if (operater.ToLower() == "like") break;
                                    temp = FieldName + getParameterExt();
                                    dbData = DBNull.Value;
                                    pKeyFieldName = new SqlParameterDeclaration(temp);
                                    SearchCond += " and " + fieldName + " " + operater + " " + pKeyFieldName.Generate() + " ";
                                    SearchParameters.Add(DbParameterFactory.DefaultFactory.CreateParameter(temp, dbData));
                                }
                                break;
                        }
                        this.CurrentPageIndex = 0;
                        return null;
                    }
                    catch
                    {
                        switch (valueType)
                        {
                            case "System.DateTime"://接受年月日形式
                                return "输入格式不正确！应当输入日期！";

                            case "System.Int16":
                                goto case "System.Int64";
                            case "System.Int32":
                                goto case "System.Int64";
                            case "System.Int64":
                                return "输入格式不正确！应当输入数字！";

                            case "System.Decimal":
                                return "输入格式不正确！应当输入数字！";

                            default:
                                return "输入格式不正确！";

                        }

                    }

                }
                return "操作错误！";
            }
            return null;
        }
        #endregion
        #region 数据绑定
        public IDbConnection Conn = null;
        public void BindData(BindDataType bindType)
        {

            LogicDB ldb = new LogicDB();
            DataAccess da = ldb.CreateDataAccessor();
            IDataReader reader;
            int recordcount = 0;
            try
            {
                if (Conn != null)
                {
                    recordcount = Convert.ToInt32(ExecuteScalar(getCountSql(),SearchParameters));
                }
                else
                {
                    recordcount = Convert.ToInt32(da.ExecuteScalar(getCountSql(), SearchParameters));
                }
            }
            catch (Exception ex)
            {
                string temp = ex.Message;
            }

            this.VirtualItemCount = recordcount;
            int pageCount = this.VirtualItemCount / this.PageSize + ((this.VirtualItemCount % this.PageSize > 0) ? 1 : 0) - 1;
            if (pageCount < 0) pageCount = 0;
            this.CurrentPageIndex = (this.CurrentPageIndex > pageCount ? pageCount : this.CurrentPageIndex);
            if (this.AllowCustomPaging)
            {


                if (bindType == BindDataType.搜索位置)
                {
                    int i = 0;
                    //重新计算分页
                    if (RecordPosition >= 0)
                    {
                        if (RecordPosition >= this.VirtualItemCount) RecordPosition = this.VirtualItemCount - 1;
                        SingleSelectPostion = RecordPosition % this.PageSize;
                        this.CurrentPageIndex = RecordPosition / this.PageSize;
                    }
                    else
                    {
                        if (KeyFeildNameList != null && KeyFeildNameList != string.Empty)
                        {
                            if (SearchParameters != null)
                                for (i = 0; i < SearchParameters.Count; i++)
                                    Parameters.Add(SearchParameters[i]);
                            IDataReader treader = da.ExecuteReader(getPositionSql(), Parameters);
                            if (treader.Read())
                            {
                                i = Convert.ToInt32(treader.GetValue(0)) - 1;
                                if (i < 0) i = 0;
                                SingleSelectPostion = i % this.PageSize;
                                this.CurrentPageIndex = i / this.PageSize;
                            }
                            treader.Close();
                        }
                    }
                }
                if (Conn != null)
                {
                    reader = ExecuteReader(getPagerSql(), SearchParameters);
                }
                else
                {
                    reader = da.ExecuteReader(getPagerSql(), SearchParameters);
                }
            }
            else
            {
                if (Conn != null)
                {
                    reader = ExecuteReader(getOrinSql(), SearchParameters);
                }
                else
                {
                    reader = da.ExecuteReader(getOrinSql(), SearchParameters);
                }
            }
            SchemaTable = reader.GetSchemaTable();
            this.DataSource = reader;

          
            try
            {
                this.DataBind();
            }
            catch
            {
#if DEBUG
                throw;
#endif
            }
            reader.Close();
        }
        public string FistKeyValue = string.Empty;
        protected override void OnItemDataBound(DataGridItemEventArgs e)
        {
            base.OnItemDataBound(e);
            //绑定头
            /*******
            if (e.Item.ItemType == ListItemType.Header)
            {
                if (this.SelectType == SelectType.MultiSelect) e.Item.Cells[0].Text = "<INPUT type=" + getCheckBoxString() + " name='" + KeyIDName + "' id='" + KeyIDName + "'  value=ALL onClick=\"AllBoxClick()\">全选";

                //增加排序按钮
                for (int j = 1; j < e.Item.Cells.Count; j++)
                {

                    string opField = string.Empty;
                    try
                    {
                        opField = ((BoundColumn)this.Columns[j]).DataField;
                    }
                    catch
                    {
                        continue;
                    }
                    int currOrderType = 0;//当前的排序类型

                    if (_orderList != null && _orderList.IndexOf(opField) >= 0)
                    {
                        int startpos = _orderList.IndexOf(opField);
                        int endpos = startpos + opField.Length;
                        bool goodbegin = false;
                        if (startpos == 0) goodbegin = true;
                        if (startpos > 0 && (_orderList[startpos - 1] == ' ' || _orderList[startpos - 1] == ',')) goodbegin = true;
                        bool goodend = false;
                        if (endpos == _orderList.Length) goodend = true;
                        if (endpos < _orderList.Length && (_orderList[endpos] == ' ' || _orderList[endpos] == ',')) goodend = true;

                        if (goodbegin && goodend)
                        {
                            string temp = _orderList.Substring(_orderList.IndexOf(opField) + opField.Length, _orderList.Length - _orderList.IndexOf(opField) - opField.Length);
                            if (temp.Trim().ToUpper().StartsWith("D")) currOrderType = 2;//desc
                            else currOrderType = 1;//asc
                        }
                    }
                    if (this.Columns[j].Visible)
                    {
                        string OrderBy = "<table cellpadding=0 cellspacing=0>	<tr><td rowspan=3 nowrap><font color=\"#c0e0e0\" >" + e.Item.Cells[j].Text +
                            "<font></td><td valign=top>";
                        if (currOrderType == 1)
                            OrderBy += "<img width=10 src='" + GetUrlRoot() + "App_Themes/Default/images/arrowupred.gif' >";
                        else
                            OrderBy += "<img src='" + GetUrlRoot() + "App_Themes/Default/images/arrowup.gif' style='CURSOR: hand' onclick=" + Page.ClientScript.GetPostBackEventReference(this, "asc|" + j) + ">";
                        OrderBy += "</td>	</tr><tr><td valign=center>";
                        if (currOrderType == 0)
                            OrderBy += "<img src='" + GetUrlRoot() + "App_Themes/Default/images/arrowcancelred.gif' >";
                        else
                            OrderBy += "<img src='" + GetUrlRoot() + "App_Themes/Default/images/arrowcancel.gif' style='CURSOR: hand' onclick=" + Page.ClientScript.GetPostBackEventReference(this, "cancelorder|" + j) + ">";
                        OrderBy += "</td></tr><tr><td valign=bottom>";
                        if (currOrderType == 2)
                            OrderBy += "<img src='" + GetUrlRoot() + "App_Themes/Default/images/arrowdownred.gif' >";
                        else
                            OrderBy += "<img src='" + GetUrlRoot() + "App_Themes/Default/images/arrowdown.gif' style='CURSOR: hand' onclick=" + Page.ClientScript.GetPostBackEventReference(this, "desc|" + j) + ">";
                        OrderBy += "</td></tr></table>";
                        e.Item.Cells[j].Text = OrderBy;
                    }
                }

            }
             */
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem) || (e.Item.ItemType == ListItemType.EditItem))
            {
                string keyvalue = string.Empty;
                int i = 0;

                for (i = 0; i < KeyIDPosition.Length; i++)
                {
                    keyvalue += e.Item.Cells[KeyIDPosition[i]].Text + "|";
                    if (i==0)
                    {
                        if (FistKeyValue == string.Empty)
                        {
                            this.FistKeyValue = e.Item.Cells[KeyIDPosition[i]].Text;

                        }
                    }
                }
                for (i = 1; i < e.Item.Cells.Count; i++)
                {
                    
                    #region AddThreeDot

                    int n = 19;
                    //加...
                    if (e.Item.Cells[i].Attributes["maxlenth"] != null)
                        n = int.Parse(e.Item.Cells[i].Attributes["maxlenth"]);
                    string tempString = e.Item.Cells[i].Text.Trim();
                    //					byte[] sarr = System.Text.Encoding.Default.GetBytes(tempString);
                    //　　				int lenall = sarr.Length;//will output as 3+3*2=9
                    //					if (lenall<=n) continue;
                    int len = 0;
                    int cutCount = n - 2;
                    for (int j = 0; j < tempString.Length; j++)
                    {
                        string str = tempString[j].ToString();
                        len += ((byte[])System.Text.Encoding.Default.GetBytes(str)).Length;
                        if (len == cutCount)
                        {
                            cutCount = j + 1;
                        }
                        else
                            if (len == cutCount + 1)
                            {
                                cutCount = j;
                            }
                        if (len >= n)
                        {
                            break;
                        }
                    }

                    if (len > n - 1)
                    {
                        e.Item.Cells[i].Text = tempString.Substring(0, cutCount) + "...";
                        e.Item.Cells[i].Attributes.Add("title", tempString);
                    }
                    #endregion

                    if (!e.Item.Cells[i].Text.Equals("&nbsp;") && !e.Item.Cells[i].HasControls()) e.Item.Cells[i].Text = HttpUtility.HtmlEncode(e.Item.Cells[i].Text);
                }

                //				for( i=0;i<KeyIDPosition.Length;i++)
                //				{
                //					keyvalue+=e.Item.Cells[KeyIDPosition[i]].Text+"|";
                //				}
                keyvalue += (this.PageSize * this.CurrentPageIndex + e.Item.ItemIndex);
                if (this.SelectType != SelectType.MultiSelect)
                {
                    string clientCallBack = string.Empty;
                    if (OnClick != null) clientCallBack = " onclick=" + Page.ClientScript.GetPostBackEventReference(this, "Click");
                    if (e.Item.ItemIndex == SingleSelectPostion)
                    {
                        ((Label)e.Item.FindControl("TempLabel")).Text = "<INPUT type=" + getCheckBoxString()
                            + " name='" + KeyIDName + "' id='" + KeyIDName + "' checked value='" + keyvalue + "'" + clientCallBack + ">";
                        KeyIDValue = keyvalue;
                    }
                    else
                        ((Label)e.Item.FindControl("TempLabel")).Text = "<INPUT type=" + getCheckBoxString()
                            + " name='" + KeyIDName + "' id='" + KeyIDName + "' value='" + keyvalue + "'" + clientCallBack + ">";
                }
                else
                {
                    ((Label)e.Item.FindControl("TempLabel")).Text = "<INPUT type=" + getCheckBoxString() + " name='" + KeyIDName + "' id='" + KeyIDName + "' value='" + keyvalue + "' onclick=\"if(!this.checked)document.all." + this.KeyIDName + "[0].checked=false;" + " \">";
                }
                e.Item.Attributes.Add("onmouseover", "this.style.cursor = 'hand';currentcolor=this.style.backgroundColor;this.style.backgroundColor='#d3d3d3'");
                e.Item.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor");
                //判断是否在前台添加了单击事件
                if (e.Item.Attributes["onclick"] == null)
                    e.Item.Attributes.Add("onclick", "this.cells(0).children(0).children(0).click();");
                else
                    e.Item.Attributes["onclick"] = "this.cells(0).children(0).children(0).click();" + e.Item.Attributes["onclick"];

                ////if (OnClick != null) e.Item.Attributes["onclick"] = Page.ClientScript.GetPostBackEventReference(this, "Click");

                if (OnDblClick != null) e.Item.Attributes.Add("ondblclick", e.Item.Attributes["ondblclick"] + ";" + Page.ClientScript.GetPostBackEventReference(this, "DblClick"));

            }

        }

        public void ExecuteQuery(string sql, DataParameterCollection parameters)
        {
            IDbCommand cmd = DbCommandFactory.DefaultFactory.CreateCommand(sql, Conn);

            if (cmd.Connection.State == ConnectionState.Closed)
            {
                cmd.Connection.Open();
            }
            PrepareCommand(cmd, parameters);
            cmd.ExecuteNonQuery();

        }
        public object ExecuteScalar(string sql, DataParameterCollection parameters)
        {
            IDbCommand cmd = DbCommandFactory.DefaultFactory.CreateCommand(sql, Conn);

            if (cmd.Connection.State == ConnectionState.Closed)
            {
                cmd.Connection.Open();
            }
            PrepareCommand(cmd, parameters);
            return cmd.ExecuteScalar();

        }
        public IDataReader ExecuteReader(string sql, DataParameterCollection parameters)
        {
            IDbCommand cmd = DbCommandFactory.DefaultFactory.CreateCommand(sql, Conn);

            if (cmd.Connection.State == ConnectionState.Closed)
            {
                cmd.Connection.Open();
            }
            PrepareCommand(cmd, parameters);
            return cmd.ExecuteReader();

        }
        private void PrepareCommand(IDbCommand command, DataParameterCollection parameters)
        {
            command.Parameters.Clear();

            if (parameters != null && parameters.Count > 0)
            {
                DataParameterCollection nParameters = new DataParameterCollection(parameters.Count);
                for (int i = 0; i < parameters.Count; i++)
                {
                    nParameters.Add(
                        DbParameterFactory.DefaultFactory.CreateParameter(
                        parameters[i].ParameterName, parameters[i].DbType));
                }
                for (int i = 0; i < parameters.Count; i++)
                {
                    nParameters[i].ParameterName = SqlDom.Generator.SqlDomGenerator.DefaultGenerator.GenerateParameterName(parameters[i]);
                    if (parameters[i].Value == null)
                        nParameters[i].Value = DBNull.Value;
                    else
                        nParameters[i].Value = parameters[i].Value;
                    if (!command.Parameters.Contains(nParameters[i].ParameterName))
                        command.Parameters.Add(nParameters[i]);
                }
            }
        }
        #endregion
        #region 配套方法
        bool isGoodKeyName(string KeyName)
        {
            if (KeyName == string.Empty) return false;
            if (KeyName.Trim().IndexOf(" ") >= 0) return false;//不能包含空格
            if (KeyName.IndexOf("%") >= 0) return false;//不能包含%
            if (KeyName.IndexOf("'") >= 0) return false;//不能包含单引号
            if (KeyName.IndexOf("=") >= 0) return false;//不能包含=号
            //检查是否在selectLis中
            //			string tempstr= (VSelectList==string.Empty)?SelectList:VSelectList;
            //			if(tempstr.IndexOf(KeyName)<0)return false;
            return true;
        }
        string getSelectFeildName(string fieldName)
        {

            if (fieldName.IndexOf('.') > 0) return fieldName;//已经带了表名
            if (fieldName.IndexOf('(') > 0) return fieldName;//已经指定是计算字段
            if (_selectList.Trim() == "*") return fieldName;//单表非计算字段

            string FieldName = fieldName.ToLower();
            string tempSelectList = _selectList.ToLower();
            tempSelectList = tempSelectList.Replace(" ,", ",");
            if (tempSelectList == null || tempSelectList == string.Empty) return FieldName;

            //if(_tableList.Split(',').Length==1 && _tableList.ToLower().IndexOf("join")<0  )return FieldName;//单表

            int start, end;
            start = 0;
            end = 0;
            tempSelectList = tempSelectList.Trim();
            if (tempSelectList.StartsWith("distinct ")) tempSelectList = tempSelectList.Remove(0, 9);
            if (tempSelectList.IndexOf(FieldName) < 0)
            {
                //不在列表中				
                end = tempSelectList.IndexOf("*");//属于*所在的表
                if (end < 0) return fieldName;//可能为非重复字段
                //猜测他在* 中
                int two = tempSelectList.IndexOf("*", end);
                if (two >= 0) return fieldName;//多个*则则放弃
                tempSelectList = tempSelectList.Substring(0, end);
                start = tempSelectList.LastIndexOf(',') + 1;
                return tempSelectList.Substring(start, end - start) + fieldName;
            }
            else
            {
                tempSelectList += ",";
                ArrayList al = splitCommaList(tempSelectList);
                for (int i = 0; i < al.Count; i++)
                {
                    string temp = al[i].ToString().Trim();
                    if (temp.EndsWith(FieldName))
                    {
                        temp = temp.TrimEnd(FieldName.ToCharArray());
                        if (temp != null && temp != string.Empty)//前面有内容
                        {
                            if (al[i].ToString().Trim().IndexOf(' ') < 0 && al[i].ToString().Trim().IndexOf(')') < 0)//非计算字段
                                return al[i].ToString().Trim();
                            else //计算字段
                            {
                                string cutfieldname = al[i].ToString().Trim().Remove(al[i].ToString().Trim().Length - FieldName.Length, FieldName.Length).Trim();
                                if (cutfieldname.LastIndexOf(" as") == cutfieldname.Length - 3) cutfieldname = cutfieldname.Remove(cutfieldname.Length - 3, 3);
                                return "(" + cutfieldname.ToUpper() + ")";
                            }
                        }
                    }
                }
                return FieldName;
            }
        }

        bool isGoodOperater(string Operater)
        {
            if (Operater == string.Empty) return false;
            if (Operater.Equals("=")) return true;
            if (Operater.Equals(">")) return true;
            if (Operater.Equals("<")) return true;
            if (Operater.Equals("<=")) return true;
            if (Operater.Equals("=>")) return true;
            if (Operater.ToLower().Equals("like")) return true;
            return false;
        }
        /// <summary>
        /// 替换/ % _ ,为escape子句做准备
        /// </summary>
        /// <param name="likevalue"></param>
        /// <returns></returns>
        string getLikeValue(string likevalue)
        {
            string tempStr = string.Empty;
            tempStr = likevalue.Replace("/", "//").Replace("%", "/%").Replace("_", "/_");
            return "%" + tempStr + "%";
        }

        /// <summary>
        /// 分解逗号表达式
        /// </summary>
        /// <param name="CommaList"></param>
        /// <returns></returns>
        ArrayList splitCommaList(string CommaList)
        {
            ArrayList al = new ArrayList();
            int i = 0;
            int j = 0;
            while (CommaList != string.Empty)
            {
                for (i = 0; i < CommaList.Length; i++)
                {
                    if (CommaList[i] == ')') j--;
                    if (CommaList[i] == '(') j++;
                    if (CommaList[i] == ',' && j == 0)
                    {
                        al.Add(CommaList.Substring(0, i));
                        CommaList = CommaList.Substring(i + 1, CommaList.Length - i - 1);
                        break;
                    }
                }
            }
            return al;
        }
        //获取参数后缀
        static long ParameterNumber = 0;
        string getParameterExt()
        {
            ParameterNumber++;
            return "A" + ParameterNumber;
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            try
            {
                SearchCond = ViewState["SearchCond"].ToString();
            }
            catch { SearchCond = ""; }
            SearchParameters = (DataParameterCollection)ViewState["SearchParameters"];
            if (SearchParameters != null)
            {
                for (int i = 0; i < SearchParameters.Count; i++)
                {
                    SearchParameters[i].Value = ViewState[SearchParameters[i].ParameterName];
                }
            }
            else
            {
                SearchParameters = new DataParameterCollection();
            }

            try
            {
                KeyIDName = ViewState["KeyIDName"].ToString();
            }
            catch { KeyIDName = ""; }
            try
            {
                _vselectList = ViewState["_vselectList"].ToString();
            }
            catch { _vselectList = ""; }
            try
            {
                _selectList = ViewState["_selectList"].ToString();
            }
            catch { _selectList = ""; }
            try
            {
                _tableList = ViewState["_tableList"].ToString();
            }
            catch { _tableList = ""; }
            try
            {
                _whereList = ViewState["_whereList"].ToString();
            }
            catch { _whereList = ""; }
            try
            {
                _groupList = ViewState["_groupList"].ToString();
            }
            catch { _groupList = ""; }
            try
            {
                _havingList = ViewState["_havingList"].ToString();
            }
            catch { _havingList = ""; }
            try
            {
                _orderList = ViewState["_orderList"].ToString();
            }
            catch { _orderList = ""; }
            try
            {
                SelectType = (SelectType)ViewState["SelectType"];
            }
            catch { SelectType = SelectType.SingleSelect; }
            try
            {
                KeyIDPosition = (int[])ViewState["KeyIDPosition"];
            }
            catch
            {
                KeyIDPosition = new int[] { 1 };
            }
            try
            {
                KeyIDValue = ViewState["KeyIDValue"].ToString();
            }
            catch { KeyIDValue = ""; }

        }
        protected override object SaveViewState()
        {
            ViewState["SearchCond"] = SearchCond;
            ViewState["SearchParameters"] = SearchParameters;
            if (SearchParameters != null)
            {
                for (int i = 0; i < SearchParameters.Count; i++)
                {
                    ViewState[SearchParameters[i].ParameterName] = SearchParameters[i].Value;
                }
            }
            ViewState["KeyIDName"] = KeyIDName;
            ViewState["_vselectList"] = _vselectList;
            ViewState["_selectList"] = _selectList;
            ViewState["_tableList"] = _tableList;
            ViewState["_whereList"] = _whereList;
            ViewState["_groupList"] = _groupList;
            ViewState["_havingList"] = _havingList;
            ViewState["_orderList"] = _orderList;
            ViewState["SelectType"] = SelectType;
            ViewState["KeyIDPosition"] = KeyIDPosition;
            ViewState["KeyIDValue"] = KeyIDValue;
            return base.SaveViewState();
        }       

        private string GetUrlRoot()
        {

            return ApplicationBase.GetUrlRoot();
        }
        #endregion
        #region 双击事件

        public event Click OnClick;
        public event DoubleClick OnDblClick;

        #region IPostBackEventHandler 成员

        public void RaisePostBackEvent(string eventArgument)
        {
            if (eventArgument == "DblClick")
            {
                if (OnDblClick != null)
                    OnDblClick();
            }
            else if (eventArgument == "Click")
            {
                if (OnClick != null)
                    OnClick();
            }
            else
            {
                string[] args = eventArgument.Split('|');
                string opField = ((BoundColumn)this.Columns[int.Parse(args[1])]).DataField;
                switch (args[0])
                {
                    case "asc":
                        if (_orderList.IndexOf(opField) < 0)
                        {
                            _orderList += "," + opField;
                        }
                        else
                        {
                            bool shouldResearch = false;
                            int start = _orderList.IndexOf(opField) + opField.Length;
                            int end = _orderList.Length;
                            for (int i = start; i < end; i++)
                            {
                                if (_orderList[start] == 'd' || _orderList[start] == 'D') shouldResearch = true;//desc 
                                if (_orderList[start] == ',') break;
                                _orderList = _orderList.Remove(start, 1);

                            }
                            if (!shouldResearch) return;
                        }
                        break;
                    case "desc":
                        if (_orderList.IndexOf(opField) < 0)
                        {
                            _orderList += "," + opField + " desc ";
                        }
                        else
                        {
                            bool shouldResearch = true;
                            int start = _orderList.IndexOf(opField) + opField.Length;
                            int end = _orderList.Length;
                            for (int i = start; i < end; i++)
                            {
                                start = i;
                                if (_orderList[i] == 'd' || _orderList[i] == 'D') { shouldResearch = false; break; }//desc
                                if (_orderList[i] == ',') break;
                                if (_orderList[i] == 'a' || _orderList[i] == 'A')
                                { _orderList = _orderList.Remove(i, 3); break; }//移去asc

                            }
                            if (!shouldResearch) return;
                            else
                            {
                                _orderList = _orderList.Insert(start, " desc");
                            }

                        }
                        break;
                    case "cancelorder":
                        if (_orderList.IndexOf(opField) < 0)
                        {
                            return;
                        }
                        else
                        {

                            int start = _orderList.IndexOf(opField);
                            _orderList = _orderList.Replace(opField, "");
                            int end = _orderList.Length;
                            for (int i = start; i < end; i++)
                            {
                                if (_orderList[start] == ',') { _orderList = _orderList.Remove(start, 1); break; }
                                _orderList = _orderList.Remove(start, 1);

                            }

                        }
                        break;
                }
                _orderList = _orderList.Trim(new char[] { ',' });
                this.BindData(BindDataType.搜索位置);
            }
        }

        #endregion

        #endregion
        #region 单击事件
        #endregion

    }
}
public delegate void Click();